<template>
	<div id="adground">
		<!-- 广告管理内容在这里进行填写 -->
		<el-row class="role-head">
			<el-input placeholder="请输入广告标题" v-model="adtitle"></el-input>
			<el-input placeholder="请输入广告内容" v-model="adcontent"></el-input>
			<el-button type="primary" icon="el-icon-search" @click="searchAd">查询</el-button>
			<el-button type="primary" icon="el-icon-edit" @click="addAdd">添加</el-button>
			<el-button type="primary" icon="el-icon-bottom" @click="downLoadExsl">导出</el-button>
		</el-row>
		<template>
			<el-table :data="tableData" style="width: 100%" :border="true" :header-cell-style="{textAlign: 'center'}"
				:cell-style="{textAlign:'center'}">
				>
				<el-table-column prop="id" label="广告ID" width="180" sortable>
				</el-table-column>
				<el-table-column prop="name" label="广告标题" width="180">
				</el-table-column>
				<el-table-column prop="content" label="广告内容">
				</el-table-column>
				<el-table-column label="广告图片">
					<template slot-scope="scope">
						<!-- <img :src="scope.row.url" class="avator2" /> -->
						<el-popover placement="right" trigger="hover">
							<img :src="scope.row.url" style="max-width: 100px;max-height: 100px" />
							<img slot="reference" :src="scope.row.url" class="avator2">
						</el-popover>
					</template>
				</el-table-column>
				<el-table-column label="广告位置" prop="position">
				</el-table-column>
				<el-table-column label="活动链接" prop="link">
				</el-table-column>
				<el-table-column label="是否启用">
					<template slot-scope="scope">
						<el-tag type="success">{{scope.row.enabled?'启用':'不启用'}}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑
						</el-button>
						<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</template>

		<template>
			<!-- 这里就是添加弹出的对话框 -->
			<el-dialog :title="flag?'创建':'编辑'" :visible.sync="dialogVisible" width="50%">
				<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
					class="demo-ruleForm" id="addfrom">
					<el-form-item label="广告标题" prop="title">
						<el-input v-model="ruleForm.title" autocomplete="off"></el-input>
					</el-form-item>
					<el-form-item label="广告内容" prop="content">
						<el-input v-model="ruleForm.content" autocomplete="off"></el-input>
					</el-form-item>
					<el-form-item label="广告图片" prop="imageUrl">
						<el-upload class="avatar-uploader" :headers="tokens"
							action="http://192.168.1.54:8080/admin/storage/create" :show-file-list="false"
							:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
							<img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar">
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1Mb</div>
						</el-upload>
					</el-form-item>
					<el-form-item label="广告位置">
						<template>
							<el-select v-model="value" placeholder="请选择">
								<el-option v-for="item in options" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</template>
					</el-form-item>
					<el-form-item label="活动链接">
						<el-input autocomplete="off" v-model="link"></el-input>
					</el-form-item>
					<el-form-item label="是否启用">
						<template>
							<el-select v-model="value2" placeholder="请选择">
								<el-option v-for="item in options2" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</template>
					</el-form-item>

				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="submitForm(ruleForm)">确 定</el-button>
				</span>
			</el-dialog>

		</template>

		<template>
			<!-- 这里是分页功能 -->
			<div class="block">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page="page" :page-sizes="[10, 20, 30, 40]" :page-size="limit"
					layout="total, sizes, prev, pager, next, jumper" :total="total">
				</el-pagination>
			</div>
		</template>



	</div>
</template>
<script>
	import {
		allAd,
		addAdground,
		upAdground,
		delAdground
	} from '../../https/promotion'
	export default {
		data() {
			let validateTitle = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('标题不能为空'));
				} else {
					// console.log("")
					callback();
				}
			};
			let validateContent = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('内容不能为空'));
				} else {
					// console.log("")
					callback();
				}
			};
			let validateImg = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('图片地址不能为空'));
				} else {
					// console.log("")
					console.log("我是图片的", value)
					callback();
				}
			};
			return {
				//广告标题
				adtitle: '',
				// 广告内容
				adcontent: '',
				// 表格的数据
				tableData: [],
				// 是否进行弹框显示
				dialogVisible: false,
				// 当前默认选中哪个页面
				page: 1,
				// 每页的限制条数
				limit: 0,
				// 总共条数
				total: 0,
				ruleForm: {
					title: '',
					content: '',
					// 上传的图片
					imageUrl: '',
				},
				// 表单的规则
				rules: {
					title: [{
						validator: validateTitle,
						trigger: 'blur',
						required: true
					}],
					content: [{
						validator: validateContent,
						trigger: 'blur',
						required: true
					}],
					imageUrl: [{
						validator: validateImg,
						trigger: 'change',
						required: true,
					}]

				},

				// 图片的token值
				tokens: {
					"X-Litemall-Admin-Token": ''
				},
				// 下拉的列表
				options: [{
					value: 1,
					label: '首页'
				}],
				// 下拉的选项
				value: 1,
				// 是否启用列表
				options2: [{
					value: true,
					label: '启用'
				}, {
					value: false,
					label: '不启用'
				}],
				value2: true,
				// 活动链接
				link: '',
				// 看选中哪个？
				flag: true,
				// 修改，删除所需的id
				userId: '',

			}
		},
		methods: {
			searchAd() {
				// 根据条件进行查找
				let params = {
					page: '',
					limit: '',
					name: this.adtitle,
					content: this.adcontent
				}
				allAd(params).then(res => {
					// 查询数据进行返回
					this.tableData = res.data.data.list
					this.total = res.data.data.total
				}).catch(err => {
					// 错误的结果
					console.log("错误的结果", err)
				})
			},
			downLoadExsl() {
				// 导出excel

				this.$confirm("此操作将导出列表excel文件, 是否继续?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						this.excelData = this.tableData; //你要导出的数据list。
						// 没有数据不能导出						
						if (this.tableData.length != 0) {
							this.export2Excel();
						} else {
							this.$message({
								showClose: true,
								message: '列表数据为空',
								type: 'warning'
							});
						}

					})
					.catch(() => {});


			},
			export2Excel() {
				var that = this;
				require.ensure([], () => {
					const {
						export_json_to_excel
					} = require("../../excel/Export2Excel"); //这里必须使用绝对路径，根据自己的命名和路径
					const tHeader = [
						// 这个是导出excel里面的表头
						"广告标题",
						"广告内容",
						"广告图片",
						"活动链接",
						"是否启用",

					]; // 导出的表头名
					const filterVal = [
						// 这个是你表格数据的字段
						"name",
						"content",
						"url",
						"link",
						"enabled",
					]; // 导出的表头字段名
					const list = that.excelData;
					// that.excelData为传入的数据
					const data = that.formatJson(filterVal, list);
					export_json_to_excel(tHeader, data, `广告管理`); // 导出的表格名称，根据需要自己命名
					// tHeader为导出Excel表头名称，`xxxxxx`即为导出Excel名称
				});
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]));
			},
			addAdd() {
				// 添加广告
				this.dialogVisible = true
				this.flag = true
				// 将数据进行清空
				// this.$refs.ruleForm.resetFields()
				this.link=''
				this.value2=true
				// this.$nextTick(()=>{
				// 				this.$refs.ruleForm.resetFields()
				// 		})
					},
			handleEdit(index, row) {
				// 编辑操作
				console.log("编辑", row);
				this.flag = false
				this.dialogVisible = true
				// 对初始值进行赋值
				this.ruleForm.title = row.name
				this.ruleForm.content = row.content
				this.ruleForm.imageUrl = row.url
				this.link=row.link
				// 拿到userId
				this.userId = row.id

			},
			handleDelete(index, row) {
				// 删除操作
				console.log("删除", row);
				this.userId = row.id
				let params = {
					id: this.userId,
					// 标题
					name: this.ruleForm.title,
					// 内容
					content: this.ruleForm.content,
					// 广告图片
					url: this.ruleForm.imageUrl,
					// 广告位置
					position: this.value,
					// 活动链接
					link: this.link,
					// 是否禁用
					enabled: this.value2
				}
				
				this.$confirm('此操作将永久删除该条目, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(() => {
					delAdground(params).then(res => {
						// console.log("上传成功", res)
						// 调用查询进行刷新
						   if(res.data.errmsg=='成功'){
								 this.$message({
								   type: 'success',
								   message: '删除成功!'
								 });
							 }
						this.selectAll()
					
					}).catch(err => {
						console.log("失败", err)
					})
					
				
				}).catch(() => {
				  this.$message({
				    type: 'info',
				    message: '已取消删除'
				  });          
				});
				
				


			},
			handleAvatarSuccess(res, file) {
				// this.imageUrl = URL.createObjectURL(file.raw);
				console.log("success???", this.ruleForm.imageUrl)
				console.log("我是file", file)
				// 这里将图片地址上传
				this.ruleForm.imageUrl = file.response.data.url
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt1M = file.size / 1024 / 1024 < 1;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt1M) {
					this.$message.error('上传头像图片大小不能超过 1MB!');
				}
				return isJPG && isLt1M;
			},

			submitForm(formName) {
				if (this.flag) {
					// console.log(this.value, "123")
					this.$refs.ruleForm.validate((valid) => {
						if (valid) {
							// alert('submit!');
							let params = {
								// 标题
								name: this.ruleForm.title,
								// 内容
								content: this.ruleForm.content,
								// 广告图片
								url: this.ruleForm.imageUrl,
								// 广告位置
								position: this.value,
								// 活动链接
								link: this.link,
								// 是否起用
								enabled: this.value2

							}
							addAdground(params).then(res => {
								// console.log("上传成功", res)
								if(res.data.errmsg=='成功'){
									this.$notify({
										title: '成功',
										message: '添加成功',
										type: 'success'
									});
									}else{
										this.$notify({
											title: '失败',
											message: '添加失败',
											type: 'error'
										});
									}
								
								this.selectAll()
							}).catch(err => {
								console.log("失败", err)
							})

							this.dialogVisible = false

						} else {
							console.log('error submit!!');
							return false;
						}
					});
				} else {
					// 调用修改的接口
					this.$refs.ruleForm.validate((valid) => {
						if (valid) {
							// alert('submit!');
							let params = {
								id: this.userId,
								// 标题
								name: this.ruleForm.title,
								// 内容
								content: this.ruleForm.content,
								// 广告图片
								url: this.ruleForm.imageUrl,
								// 广告位置
								position: this.value,
								// 活动链接
								link: this.link,
								// 是否禁用
								enabled: this.value2

							}
							upAdground(params).then(res => {
								console.log("修改成功", res)
								if(res.data.errmsg=='成功'){
									this.$notify({
										title: '成功',
										message: '修改成功',
										type: 'success'
									});
									}else{
										this.$notify({
											title: '失败',
											message: '修改失败',
											type: 'error'
										});
									}
								this.selectAll()
							}).catch(err => {
								console.log("失败", err)
							})

							this.dialogVisible = false

						} else {
							console.log('error submit!!');
							return false;
						}
					})
				}

			},
			//获取所有的广告
			selectAll() {
				allAd().then(res => {
					this.tableData = res.data.data.list
					this.total = res.data.data.total
					// 我是挂载产生的数据
					console.log("我是挂载产生的数据", res)
				}).catch(err => {
					console.log("我是挂载失败", err)
				})
			},

			handleSizeChange(val) {
				// 分页改变显示数据
				// console.log(`每页 ${val} 条`);
				this.limit = val
				let params = {
					page: '',
					limit: this.limit
				}
				allAd(params).then(res => {
					this.tableData = res.data.data.list
					this.total = res.data.data.total
					// 我是挂载产生的数据
					console.log("我是挂载产生的数据", res)
				}).catch(err => {
					console.log("我是挂载失败", err)
				})
			},
			handleCurrentChange(val) {
				// 当前页码的数据
				// console.log(`当前页: ${val}`);
				this.page = val
				let params = {
					page: this.page,
				}
				allAd(params).then(res => {
					// console.log("每页100条", res)
					this.tableData = res.data.data.list
					this.total = res.data.data.total
				}).then(err => {

				})
			},


		},
		mounted() {
			// 这里进行挂载
			// allAd().then(res => {
			// 	this.tableData = res.data.data.list
			// 	// 我是挂载产生的数据
			// 	console.log("我是挂载产生的数据", res)
			// }).catch(err => {
			// 	console.log("我是挂载失败", err)
			// })
			this.selectAll()
			// 将token值进行存储
			this.tokens["X-Litemall-Admin-Token"] = this.Cookies.get('token')
			
		},
		// watch: {
		// 	dialogVisible(newValue, older){
		// 		// 监听变化清空列表
		// 		this.$nextTick(()=>{
		// 				this.$refs.ruleForm.resetFields()
		// 		})
			
		// 	}
		// }
	}
</script>

<style>
	.role-head {
		margin-bottom: 15px;
		min-width: 500px;
		overflow: hidden;
	}

	.role-head .el-input {
		width: 150px !important;
		margin-right: 10px;
	}

	.avator2 {
		/* 头像的处理 */
		width: 40px;
		height: 40px;
	}

	/* 表单里面的输入框 */
	#addfrom .el-input__inner {
		width: 450px;
	}

	#addfrom .el-form-item__label {
		font-weight: bolder;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 120px;
		height: 120px;
		line-height: 120px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.block {
		margin-top: 20px;
	}
</style>
